import { JSX, useEffect, useState } from 'react'
import { Button, Table } from 'antd'

const { Column } = Table

interface DataType {
  key: React.Key
  ID: number
  NAME: string
  EMAIL: string
}

const AppTable = (): JSX.Element => {
  const [dataSource, setDataSource] = useState<DataType[]>([])

  useEffect(() => {
    getList()
  }, [])

  const pushClick = (): void => {
    window.electron.ipcRenderer
      .invoke('userAdd', { name: '张三', email: 'zhangsan@example.com' })
      .then((res) => {
        if (res.code === 200) {
          getList()
        }
      })
  }

  const delClick = (id: number): void => {
    window.electron.ipcRenderer.invoke('userDel', { id }).then((res) => {
      if (res.code === 200) {
        getList()
      }
    })
  }

  function getList(): void {
    window.electron.ipcRenderer.invoke('userList').then((res: DataType[]) => {
      setDataSource(res)
    })
  }

  return (
    <div>
      <Button onClick={pushClick}>添加</Button>
      <Table<DataType> dataSource={dataSource} pagination={false}>
        <Column title={'id'} dataIndex={'ID'} key={'ID'}></Column>
        <Column title={'名称'} dataIndex={'NAME'} key={'NAME'}></Column>
        <Column title={'邮箱'} dataIndex={'EMAIL'} key={'EMAIL'}></Column>
        <Column
          title={'操作'}
          render={(_, record) => {
            return (
              <Button danger onClick={() => delClick(record.ID)}>
                删除
              </Button>
            )
          }}
        ></Column>
      </Table>
    </div>
  )
}
export default AppTable
